import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, Row, Col, Spin, message } from 'antd';
import { WeaDialog, WeaSearchGroup, WeaUpload, WeaTools, WeaInput, WeaInputNumber, WeaDatePicker, WeaError, WeaHelpfulTip, WeaLocaleProvider, WeaFormItem } from 'ecCom';
import { WeaSwitch } from 'comsMobx';
import { RenderForm, FormatDate } from '../util';

const { viewer } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;

@inject('listStore', 'newStore')
@observer
export default class NewGroupVoting extends Component {
  constructor(props) {
    super(props);
    this.classPrefix = 'group-voting-list-new';
  }

  onCancel = () => {
    const { listStore, newStore } = this.props;
    const { setStoreState } = listStore;
    setStoreState({ newVisible: false });
    newStore.newGroupVoteForm.resetForm();
    newStore.clearNewVote();
  }

  getForm = (form, fields) => {
    const { isFormInit } = form;
    const { checkmode } = form.getFormParams();
    let group = [];
    isFormInit && fields && fields.map((c) => {
      let items = [];
      c.items.map((field,index) => {
        if (field.domkey[0] === 'themepic') {
          items.push({ com: RenderForm(form, field, '', this.renderUpload(), '', true) });
        } else if (field.domkey[0] === 'groupvotename') {
          const preCls = 'group-vote-form';
          items.push({
            com: (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@fg6drx@${(field.domkey && field.domkey[0]) ? field.domkey[0] : `fg6drx${index}`}`}
                label={`${field.label}`}
                labelCol={{ span: `${field.labelcol}` }}
                wrapperCol={{ span: `${field.fieldcol}` }}
                className={`${preCls}-formItem ${preCls}-${(field.domkey && field.domkey[0]) ? field.domkey[0] : ''}`}
                error={form.getError(field)}
                tipPosition="bottom"
              >
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@80v813@${(field.domkey && field.domkey[0]) ? field.domkey[0] : `80v813${index}`}`}>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@l3z68c@${(field.domkey && field.domkey[0]) ? field.domkey[0] : `l3z68c${index}`}`} span={19}>
                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@623ubd@${(field.domkey && field.domkey[0]) ? field.domkey[0] : '623ubd'}`}
                      fieldConfig={field}
                      form={form}
                    />
                  </Col>
                </Row>
              </WeaFormItem>
            ),
          });
        } else if (field.domkey[0] === 'checkmode') {
          if (checkmode === '1') {
            items.push({ com: RenderForm(form, field, '', this.renderMode()) });
          } else {
            items.push({ com: RenderForm(form, field) });
          }
        } else if (field.domkey[0] === 'maxvoteoption') {

        } else if (field.domkey[0] === 'voteoption') {
          items.push({ com: RenderForm(form, field, '', this.renderVoteOpts(), '', true) });
        } else if (field.domkey[0] === 'votesec') {
          items.push({ com: RenderForm(form, field, '', <span className="tip">({getLabel('513725', '只有发布者才可查看投票人统计')})</span>, '') });
        } else if (field.domkey[0] === 'voteendtime') {
          items.push({ com: RenderForm(form, field, '', this.renderEndDate(), '', true) });
        } else {
          items.push({ com: RenderForm(form, field) });
        }
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@at2130@Form_WeaSearchGroup`} col={1} needTigger={true} showGroup={c.defaultshow} items={items} />);
    });
    return group;
  }

  /* 主题图片 */
  renderUpload = () => {
    const { newStore: { themeImage, setStoreState } } = this.props;
    if (toJS(themeImage).length > 0) {
      const { imgSrc, fileid } = toJS(themeImage)[0];
      return (
        <div className={`${this.classPrefix}-themeImg`}>
          <img
            data-imgsrc={imgSrc}
            ref={fileid}
            src={imgSrc}
            className="formImgPlay"
            onClick={viewer}
          />
          <i className="icon-coms-Clear" onClick={() => setStoreState({ themeImage: [] })} />
        </div>
      );
    }
    return (
      <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@isau58`}
        btnSize="small"
        uploadUrl="/api/groupchatvote/upload/uploadImgForGroupLoad"
        category="string" // 文件上传目录
        isDetail
        multiSelection={false}
        maxFilesNumber={1}
        limitType={'jpg,gif,png,jpeg'}
        onChange={(ids, list) => setStoreState({ themeImage: list })}
        className={`${this.classPrefix}-uploadImg`}
      />
    );
  }

  /* 选择模式 */
  renderMode = () => {
    const { newStore: { maxvoteoption, setStoreState } } = this.props;
    return (
      <span className={`${this.classPrefix}-inputNum`}>
        {getLabel('83958', '最多')}
        <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@v588jp`} tipPosition="top" ref="maxoption" error={getLabel('516463', '最多可填选项未填写')}>
          <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@0qybo6`}
            className="input"
            min={0}
            defaultValue={2}
            value={maxvoteoption}
            viewAttr={3}
            onChange={v => setStoreState({ maxvoteoption: v })}
          />{getLabel('26302', '项')}
        </WeaError>
        <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@8lng06`} title={getLabel('516173', '输入0表示不限制')} placement="topLeft" />
      </span>
    );
  }

  /* 投票选项 */
  renderVoteOpts = () => {
    const { newStore: { voteOptions } } = this.props;
    return (
      <div className={`${this.classPrefix}-voteOptions`}>
        {
          toJS(voteOptions) && Object.keys(toJS(voteOptions)).map(key => this.renderOptionItem(toJS(voteOptions)[key], key > 2, key))
        }
        <a onClick={e => this.addOption(e)}>{getLabel('502268', '添加选项')}</a>
      </div>
    );
  }

  renderOptionItem = (data, isExtra = false, key) => {
    const { newStore: { onOptImageChange, voteOptions, deleteOptImg, onOptContentChange } } = this.props;
    const judgeOpts = toJS(voteOptions) && toJS(voteOptions[data.key]);
    let item = [
      <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@edkumt@${key}`} className={`${this.classPrefix}-voteOptions-item`}>
        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ozwzm7@${key}`} span={19}>
          <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@qk942d@${key}`} tipPosition="bottom" ref={`optInpt${data.key}`} error={getLabel('516174', '投票选项未填写')}>
            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@kdqwnu@${key}`}
              viewAttr={3}
              placeholder={`${getLabel('386817', '选项')}${data.key}`}
              value={judgeOpts && toJS(voteOptions[data.key].content) || ''}
              onChange={v => onOptContentChange(v, data)}
            />
          </WeaError>
        </Col>
        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@nbhjer@${key}`} span={3} className="addImage">
          <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@zoblvx@${key}`}
            btnSize="small"
            uploadUrl="/api/groupchatvote/upload/uploadImgForGroupLoad"
            category="string" // 文件上传目录
            limitType={'jpg,gif,png,jpeg'}
            datas={judgeOpts && toJS(voteOptions[data.key].imageData) || []}
            onChange={(ids, list, allList) => onOptImageChange(ids, list, data, allList)}
          >
            <i className="icon-portal-photo-o" />
          </WeaUpload>
        </Col>
        { isExtra && <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@p9695d@${key}`} span={2}><i className="icon-coms02-Delete" onClick={() => this.deleteOption(data.key)} /></Col> }
      </Row>,
    ];
    if (judgeOpts && toJS(voteOptions[data.key].imageArr) && toJS(voteOptions[data.key].imageArr).length > 0) {
      let renderImage = toJS(voteOptions[data.key].imageArr).map((item) => {
        const { fileid, imgSrc } = item;
        return (
          <div className={`${this.classPrefix}-voteOptions-optionImg-item`} key={fileid}>
            <img
              data-imgsrc={imgSrc}
              ref={fileid}
              src={imgSrc}
              className="formImgPlay"
              onClick={viewer}
            />
            <i className="icon-coms-Clear" onClick={() => deleteOptImg(fileid, data)} />
          </div>
        );
      });
      item.push(<div className={`${this.classPrefix}-voteOptions-optionImg`}>{renderImage}</div>);
    }
    return item;
  }

  /* 投票截止时间 */
  renderEndDate = () => {
    const { newStore: { finishTime, setStoreState } } = this.props;
    let nowTime = FormatDate(new Date(), 'yyyy-MM-dd HH:mm');
    let dayTime = new Date().getDate();
    let hourTime = new Date().getHours();
    let secondTime = new Date().getMinutes();
    return (
      <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@vu2zlh`} tipPosition="bottom" ref="datePick" error={getLabel('516175', '截止时间为空')}>
        <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@9ch8ut`}
          showTime={{ format: 'HH:mm' }}
          format="yyyy-MM-dd HH:mm"
          needSecond
          startValue={nowTime}
          value={finishTime}
          onChange={v => setStoreState({ finishTime: v })}
          viewAttr={3}
          disabledTimeConfig={{
            dayConfig: {
              [dayTime]: {
                disabledHour: this.range(0, hourTime),
                HourConfig: {
                  [hourTime]: {
                    disabledMinute: this.range(0, secondTime),
                    minuteConfig: {
                      [secondTime]: [11],
                    },
                  },
                },
              },
            },
          }}
        />
      </WeaError>
    );
  }

  range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }

  /* 添加选项 */
  addOption = (e) => {
    e.preventDefault();
    const { newStore: { voteOptions, setStoreState } } = this.props;
    const optArr = Object.keys(toJS(voteOptions));
    const objectKey = Number(optArr[optArr.length - 1]) + 1;
    setStoreState({ voteOptions: { ...voteOptions, [objectKey]: { key: objectKey, imageArr: [] } } });
  }

  /* 删除选项 */
  deleteOption = (option) => {
    const { newStore: { voteOptions, setStoreState } } = this.props;
    let newOptions = toJS(voteOptions);
    delete newOptions[option];
    setStoreState({ voteOptions: newOptions });
  }

  publishVote = () => {
    const { listStore: { setStoreState, getGroupVoteList, groupid, isgroup, viewGroupVote, groupListStore }, newStore } = this.props;
    const { voteOptions, publishVote, finishTime, maxvoteoption, newGroupVoteForm } = newStore;
    let formParams = newGroupVoteForm.getFormParams();
    if (finishTime === '') {
      this.refs.datePick.showError();
      return;
    }
    if (formParams.checkmode === '1' && (!String(maxvoteoption) || Number.isNaN(Number(maxvoteoption)) || Number(maxvoteoption) < 0)) {
      this.refs.maxoption.showError();
      return;
    }
    if (Number(maxvoteoption) > Object.keys(toJS(voteOptions)).length) {
        message.error(getLabel('516749', '最多可选项数不能超过选项个数'));
        return;
    }
    for (let v in toJS(voteOptions)) {
      if (!(toJS(voteOptions)[v].content) || toJS(voteOptions)[v].content.trim() === '') {
        this.refs[`optInpt${v}`].showError();
        return;
      }
    }

    let params = { isgroup, groupid };
    publishVote(params, ({ groupChatAdd: { votingid, votetheme, enddate, endtime, themeimagesrc } }) => {
      getGroupVoteList('', true, () => {
        groupListStore.tableUpdate({ showCheck: false });
        groupListStore.setRowCheckKey([votingid]);
      });
      setStoreState({ newVisible: false, isShowDetail: true, voteId: votingid });
      viewGroupVote({ votingid });
      this.onCancel();
      if (window.em) {
        em.sendMsg({
          targetId: '', // 消息会话ID
          msgType: 10, // 消息类型：1-文本 2-链接 10-E6分享消息
          msgInfo: {
            content: votetheme, // 分享标题（必填）
            desc: `${getLabel('18111', '截止时间：')} ${enddate} ${endtime}`, // 分享描述（非必填）
            canforward: 0, // 消息是否允许转发 1：是（默认） 0：否
            callbackurl: '', // 消息转发回调地址（非必填）
            sharetypename: getLabel('514291', '群投票'), // 消息类型显示标题，没有则按sharetype显示
            sharetypeicon: '', // 消息类型显示图标
            sharetypebgcolor: '', // 消息类型背景颜色，没有则按sharetype显示
            showimage: themeimagesrc, // 消息显示图片地址，没有则不显示图片
            linkurl: `/spa/groupVote/static4mobile/index.html#/voting/${votingid}`, // 消息链接地址（必填）
            linkurl_pc: `/spa/smallApp/static/index.html#/main/groupVoting/groupVotingList?id=${votingid}`, // PC端消息链接地址，如果没有则取linkurl值
            sharetype: 'voting', // 分享数据类型,值有"doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
            shareid: votingid, // 分享的数据ID（必填）
            opentype: 1, // 移动端打开方式 1:app内打开（默认） 2：手机默认浏览器打开
            opentype_pc: 1, // PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
          },
          success: (res) => {
            // console.log('success',res)
          },
          fail: (res) => {
            // console.log('fail',res)
          },
        });
      }
    });
  }

  render() {
    const { listStore: { newVisible }, newStore } = this.props;
    const { newGroupVoteForm, newGroupVoteFields, newGroupVoteLoading, publishLoading } = newStore;
    const buttons = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7620it@publishBtn`}
        type="primary"
        className={'btnprimary'}
        onClick={this.publishVote}
        loading={publishLoading}
        disabled={publishLoading}
      >{getLabel('114', '发布')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h39dy8@closeBtn`}
        onClick={this.onCancel}
        loading={publishLoading}
        disabled={publishLoading}
      >{getLabel('31129', '取消')}</Button>,
    ];
    if (newVisible) {
      window.setDialogFullWindow = false;
    }
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@jbzmp6`}
        title={getLabel('513883', '发起新投票')}
        icon="icon-portal-reportform"
        iconBgcolor="#0079DE"
        className={this.classPrefix}
        visible={newVisible}
        style={{ width: 700, height: 350 }}
        buttons={buttons}
        onCancel={this.onCancel}
        hasScroll
      >
        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@aifpbe`} spinning={newGroupVoteLoading}>
          <div className={`${this.classPrefix}-formcontainer`}>
            { this.getForm(newGroupVoteForm, toJS(newGroupVoteFields)) }
          </div>
        </Spin>
      </WeaDialog>
    );
  }
}
